package cn.kgc.tangcco.service.impl;

import cn.kgc.tangcco.dao.DujitangMongoDao;
import cn.kgc.tangcco.mapper.DujitangMapper;
import cn.kgc.tangcco.model.ResponseText;
import cn.kgc.tangcco.model.ResultCode;
import cn.kgc.tangcco.pojo.Dujitang;
import cn.kgc.tangcco.service.DujitangService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author 李昊哲
 * @Description
 * @create 2020/12/29 14:52
 */
@Service
public class DujitangServiceImpl implements DujitangService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private DujitangMapper dujitangMapper;

    @Resource
    private DujitangMongoDao dujitangMongoDao;

    @Override
    public List<Dujitang> queryAll() {
        return dujitangMapper.selectList(new QueryWrapper<Dujitang>());
    }

    @Override
    public ResponseText<Dujitang> queryRandom(String token) {
        if (!stringRedisTemplate.hasKey(token)) {
            return new ResponseText<>(ResultCode.NO_LOGIN.getCode(),ResultCode.NO_LOGIN.getMsg(), null);
        }
        Long count = dujitangMongoDao.selectCount();
        List<Dujitang> dujitangs = dujitangMongoDao.select((int) ThreadLocalRandom.current().nextLong(count), 1);
        if (dujitangs != null && dujitangs.size() > 0) {
            return new ResponseText<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(), dujitangs.get(0));
        }
        Dujitang dujitang = new Dujitang();
        dujitang.setText("桃李不言下自成蹊");
        return new ResponseText<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(), dujitang);
    }

}
